import { getUserProfile, login } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
// import { resetRouter } from '@/router'

const state = {
  token: getToken() || '',
  userInfo: {}

}

const mutations = {
  // 持久化token,存到vuex
  setToken(state, newToken) {
    setToken(newToken)
    state.token = newToken
  },
  // 清空本地token和vuex中的
  removeToken(state) {
    removeToken()
    state.token = ''
  },

  // 获取用户信息
  getInfo(state, userInfo) {
    state.userInfo = userInfo
  }
}

const actions = {
  // 登录信息获取token存储到vuex
  async login(context, payload) {
    const token = await login(payload)
    // console.log(res)
    context.commit('setToken', token)
  },

  // 请求获取用户信息
  async getUserProfile(context) {
    const res = await getUserProfile()
    // console.log(userInfo)
    context.commit('getInfo', res.userInfo)
  },

  // 点击退出登录,清空token和用户信息
  logout(context) {
    context.commit('removeToken')
    context.commit('getInfo', {})
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

